# -*- coding: utf-8 -*-

from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save

from achievements.models import Evidence

import uuid, os

def make_uuid():
    return str(uuid.uuid4())


def get_upload_path(instance, filename):
    return os.path.join('users/', '%d' % instance.id, filename)

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    user_points = models.IntegerField(default=0)
    uuid = models.CharField(max_length=36, unique=True, default=make_uuid, editable=False)
    friends = models.ManyToManyField("self", null=True, blank=True)
    image = models.ImageField(upload_to=get_upload_path, null = True, blank=True)
    description = models.TextField()
    
    @property
    def has_new_messages(self):
        return len(list(Messages.objects.filter(recipient = self, read = False))) > 0
    
    @property
    def get_messages_count(self):
        messages = Messages.objects.filter(recipient = self)
        return len(list(messages))
    
    @property
    def get_new_messages_count(self):
        messages = Messages.objects.filter(recipient = self, read = False)
        return len(list(messages))
    
    def __unicode__(self):
        return self.user.username

class Messages(models.Model):
    recipient = models.ForeignKey(User, related_name='+')
    author = models.ForeignKey(User, related_name='+', null=True, blank=True)
    header = models.TextField(default='Správa')
    text = models.TextField(null=True, blank=True)
    read = models.BooleanField(default=False)
    send_date = models.DateTimeField('date sent', auto_now_add=True)
    evidence = models.OneToOneField(Evidence, null=True, blank=True, on_delete=models.SET_NULL)
    
    TYPES = (
        ('AM', 'Admin message'),
        ('UM', 'User message'),
        ('FR', 'Friend request'),
        ('EM', 'Evidence message')
    )
    
    message_type = models.CharField(max_length=2, choices=TYPES, default='AM')
    
    hidden = models.BooleanField(default=False)
    
    def __unicode__(self):
        return self.header
    
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        UserProfile.objects.create(user=instance)

post_save.connect(create_user_profile, sender=User)
